/*
 * GLComponent.cpp
 *
 *  Created on: Aug 5, 2010
 *      Author: Ry
 */

#include <gl/glew.h>
#include "GLComponent.h"
#include "GLGUI.h"

GLComponent::GLComponent(ShaderProgram *shaderProgram): Component() {
	this->shaderProgram = shaderProgram;
	backgroundTexture = NULL;
}

void GLComponent::draw() {
	GLint handle = shaderProgram->getHandle();
	GLint locColor = glGetAttribLocation(handle, "color");
	GLint locTexuv = glGetAttribLocation(handle, "texuv");
	GLint locBackgroundTexture = glGetUniformLocation(handle, "backgroundTexture");
	GLint locUseBackgroundTexture = glGetUniformLocation(handle, "useBackgroundTexture");

	glUseProgram(handle);
	glDisable(GL_DEPTH_TEST);

	glTranslatef((float)rect.x, (float)rect.y, 0);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	RGBA color = RGBA(0x666666, 1.0f);
	glVertexAttrib4fv(locColor, backgroundColor.getValue());

	// Background image stuff
	if (backgroundTexture != NULL) {
		glEnable(GL_TEXTURE_2D);
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, backgroundTexture->getHandle());

		glUniform1i(locUseBackgroundTexture, true);
		glUniform1i(locBackgroundTexture, 0);
	} else {
		glDisable(GL_TEXTURE_2D);
	}

	glBegin(GL_QUADS);

	glVertexAttrib2f(locTexuv, 0, 0);
	glVertex2i(0, 0);

	glVertexAttrib2f(locTexuv, 1, 0);
	glVertex2i(rect.width, 0);

	glVertexAttrib2f(locTexuv, 1, 1);
	glVertex2i(rect.width, rect.height);

	glVertexAttrib2f(locTexuv, 0, 1);
	glVertex2i(0, rect.height);

	glEnd();

	glDisable(GL_TEXTURE_2D);
	glUniform1i(locUseBackgroundTexture, false);

	if (drawBorder) {
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		glVertexAttrib4fv(locColor, borderColor.getValue());
		glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
		glBegin(GL_QUADS);
		glVertex2i(0, 0);
		glVertex2i(rect.width, 0);
		glVertex2i(rect.width, rect.height);
		glVertex2i(0, rect.height);
		glEnd();
	}

	for (unsigned int i = 0; i < children.size(); i++) {
		glLoadIdentity();
		children[i]->draw();
	}

	glEnable(GL_DEPTH_TEST);
}

GLComponent::~GLComponent() {
}
